package middleware

import (
	"gin_framework/global"
	"gin_framework/models/res"
	ctype "gin_framework/models/type"
	"gin_framework/utils/jwts"
	"github.com/gin-gonic/gin"
)

func JwtAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			res.FailWithMsg("未携带token", c)
			c.Abort()
			return
		}
		claims, err := jwts.ParseToken(token)
		if err != nil {
			res.FailWithMsg("token错误", c)
			c.Abort()
			return
		}
		// 判断是否在redis
		keys := global.Redis.Keys("logout_*").Val()
		isList("logout_"+token, keys)
		c.Set("claims", claims)
	}
}

func JwtAuthAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			res.FailWithMsg("未携带token", c)
			c.Abort()
			return
		}
		claims, err := jwts.ParseToken(token)
		if err != nil {
			res.FailWithMsg("token错误", c)
			c.Abort()
			return
		}
		if claims.Role != ctype.PermissionAdmin {
			res.FailWithMsg("权限错误!", c)
			c.Abort()
			return
		}
		c.Set("claims", claims)
	}
}

func isList(key string, list []string) bool {
	for _, s := range list {
		if s == key {
			return true
		}
	}
	return false
}
